package com.exp04;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

@WebServlet(name="GuessNumberServlet",value = "/guess")
public class GuessNumberServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int Number=new Random().nextInt(100)+1;
        HttpSession session = req.getSession();
        session.setAttribute("num",Number);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<html><head><title>guess number</title></head><body style=\"text-align:center;font-family:'FiraCode Nerd Font',serif\">");
        out.println("Please guess a number,the number is between 1 and 100!");
        out.println("<form action=\"\" method=\"post\"><input type=\"text\" name=\"guess\">");
        out.println("<input type=\"submit\" value=\"提交\"></body></html>");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int guess= Integer.parseInt(req.getParameter("guess"));
        HttpSession session=req.getSession();
        int Number= (int) session.getAttribute("num");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<html><head><title>guess number</title></head><body style=\"text-align:center;font-family:'FiraCode Nerd Font',serif\">");

        if (guess!=Number){
        if(guess<Number){
            out.println("It's too little,please try again! ");
        }
        else
        {
            out.println("It's too large,please try again! ");
        }
        out.println("<form action=' ' method='post'> ");
        out.println("<input type='text' name='guess'>");
        out.println("<input type='submit' value='submit'>");}
        else {
            session.invalidate();
            out.println("Congratulation,you're right! ");
            out.println("<a href=' '>Guess again</a>");
        }
        out.println("</form></body></html>");
    }
}
